#!/bin/bash

# 用户可配置变量（按需修改） 
NACOS_VERSION="2.3.1"                   # Nacos版本
INSTALL_DIR="/usr/local"                # 安装目录
MYSQL_ROOT_PASSWORD="Test@123"       # MySQL root密码（根据实际情况修改）
MYSQL_NACOS_PASSWORD="nacos"     # Nacos数据库用户密码
MYSQL_HOST="14.44.128.120"                  # MySQL主机地址（若远程请修改）
MYSQL_PORT="18306"                      # MySQL端口
JAVA_TAR="jdk-8u202-linux-x64.tar.gz"   # Java 8安装包名称
JAVA_DOWNLOAD_URL="https://repo.huaweicloud.com/java/jdk/8u202-b08/jdk-8u202-linux-x64.tar.gz"
NACOS_URL="14.44.128.120"

# 安装Java环境（自动检测）  
install_java() {
    # 检查是否已安装Java
    if type java >/dev/null 2>&1; then
        echo "检测到已安装Java，跳过安装。"
        return 0
    fi

    echo "未检测到Java环境，开始安装Java 8..."
    # 下载Java 8
    if [ ! -f "${JAVA_TAR}" ]; then
        wget -q "${JAVA_DOWNLOAD_URL}" -O "${JAVA_TAR}" || {
            echo "下载Java失败，请检查网络或URL！"
            exit 1
        }
    fi

    # 解压到安装目录
    sudo tar -zxvf "${JAVA_TAR}" -C "${INSTALL_DIR}"
    JAVA_HOME_DIR=$(ls -d ${INSTALL_DIR}/jdk1.8.0_202* 2>/dev/null | head -n 1)
    if [ -z "${JAVA_HOME_DIR}" ]; then
        echo "Java解压失败，请检查压缩包！"
        exit 1
    fi

    # 配置环境变量
    echo "配置Java环境变量..."
    sudo tee -a /etc/profile <<EOF

# Java Environment
export JAVA_HOME=${JAVA_HOME_DIR}
export PATH=\$JAVA_HOME/bin:\$PATH
EOF

    # 立即生效
    source /etc/profile

    # 验证安装
    java -version || {
        echo "Java安装失败！"
        exit 1
    }
}

# Nacos安装与配置 
install_nacos() {
    NACOS_PKG_NAME="nacos-server-${NACOS_VERSION}.tar.gz"
    DOWNLOAD_URL="https://github.com/alibaba/nacos/releases/download/$NACOS_VERSION/$NACOS_PKG_NAME"

    
    # 检查Nacos安装包是否存在
    if [ -f "${NACOS_PKG_NAME}" ]; then
        echo "检测到Nacos安装包已存在，跳过下载..."
    else
        # 下载Nacos
        wget -q "${DOWNLOAD_URL}" -O "${NACOS_PKG_NAME}" || {
            echo "Nacos下载失败，请检查版本号或网络连接！"
            exit 1
        }
    fi

    sudo tar -zxvf "${NACOS_PKG_NAME}" -C "${INSTALL_DIR}"
#    sudo mv "${INSTALL_DIR}/nacos" "${INSTALL_DIR}/nacos-server"
}

configure_nacos() {
    local secret_key=$(openssl rand -base64 48 | tr -d '/+=\n' | cut -c1-64)
    local config_file="${INSTALL_DIR}/nacos/conf/application.properties"

    echo "生成安全密钥并配置Nacos..."
    sudo cp "${config_file}" "${config_file}.bak"
    #匹配将其进行注释
    sed -i '/nacos.core.auth.enabled=false/ s/^/#/ ' ${INSTALL_DIR}/nacos/conf/application.properties
    sed -i '/nacos.core.auth.plugin.nacos.token.secret.key=/ s/^/#/ ' ${INSTALL_DIR}/nacos/conf/application.properties
    sed -i '/nacos.core.auth.server.identity.key=/ s/^/#/ ' ${INSTALL_DIR}/nacos/conf/application.properties
    sed -i '/nacos.core.auth.server.identity.value=/ s/^/#/ ' ${INSTALL_DIR}/nacos/conf/application.properties
    sudo tee -a "${config_file}" <<EOF
#端口修改为18848
#server.port=18848
# 数据库配置
spring.datasource.platform=mysql
db.num=1
db.url.0=jdbc:mysql://${MYSQL_HOST}:${MYSQL_PORT}/nacos?characterEncoding=utf8&connectTimeout=1000&socketTimeout=3000&autoReconnect=true
db.user.0=nacos
db.password.0=${MYSQL_NACOS_PASSWORD}

# 鉴权配置
nacos.core.auth.enabled=true
nacos.core.auth.plugin.nacos.token.secret.key==${secret_key}
nacos.core.auth.server.identity.key=security
nacos.core.auth.server.identity.value=identity
EOF
}

# 数据库初始化（使用现有MySQL） 
init_database() {
    echo "正在初始化Nacos数据库..."
    
    # 检查MySQL连接
    if ! mysql -u root -p${MYSQL_ROOT_PASSWORD} -h ${MYSQL_HOST} -P ${MYSQL_PORT} -e "SELECT 1" >/dev/null 2>&1; then
        echo "MySQL连接失败，请检查root密码、主机或端口配置！"
        exit 1
    fi

    # 执行数据库初始化
    mysql -u root -p${MYSQL_ROOT_PASSWORD} -h ${MYSQL_HOST} -P ${MYSQL_PORT} <<SQL
CREATE DATABASE IF NOT EXISTS nacos CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
CREATE USER IF NOT EXISTS 'nacos'@'%' IDENTIFIED BY '${MYSQL_NACOS_PASSWORD}';
GRANT ALL PRIVILEGES ON nacos.* TO 'nacos'@'%';
FLUSH PRIVILEGES;
SQL

    echo "导入Nacos SQL表结构..."
    NACOS_SQL_FILE="${INSTALL_DIR}/nacos/conf/mysql-schema.sql"
    if [ -f "${NACOS_SQL_FILE}" ]; then
        mysql -u root -p${MYSQL_ROOT_PASSWORD} -h ${MYSQL_HOST} -P ${MYSQL_PORT} nacos < "${NACOS_SQL_FILE}"
    else
        echo "错误：未找到SQL文件 ${NACOS_SQL_FILE}，请检查Nacos解压路径！"
        exit 1
    fi
}

# 服务启动
start_nacos() {
    echo "启动Nacos（单机模式）..."
    sh "${INSTALL_DIR}/nacos/bin/startup.sh" -m standalone
}

# 主流程 
main() {
    install_java
    install_nacos
    init_database
    configure_nacos
    start_nacos
    echo "安装完成！访问地址：http://${NACOS_URL}:8848/nacos"
}

main